﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;

using segDroopyEyes.Eco.Services.XmlQueryService2;
using Axiom;
using Axiom.Core;
using Axiom.Graphics;
using Axiom.Configuration;
using Axiom.Math;
using Axiom.Overlays;
using Axiom.Input;
using Axiom.Animating;
using IDE;
using CommonClasses;
using CommonClasses.Utility;
using CommonClasses.Logger;

using VisualDM.Model;
using Visualizator;

namespace VDMEditor
{
    public partial class VDMEditor : Form
    {
        private ILoggingManagement main_log;
        private ILogger worklog;
        private IDEEcoSpace ecoSpace;
        private KeyPressMessageFilter keyFilter;
        private Visualizator.Visualizator VisualManager;
        SceneObject SelectedObject;
        VisualDM.Model.Animation SelectedScript;
        SceneObject SwapObject=null;

        public VDMEditor()
        {
            main_log = LoggerManager.CreateOnce(".\\LoggerManager.ih.config", ".\\logs");
            worklog = main_log.GetLogger("CommandListsLogger");

            InitializeComponent();

            ecoSpace = new IDEEcoSpace(worklog);
            ecoSpace.Active = true;

                InitializeMessageFilter();
            var loader =  new VisualDMLoader(ecoSpace);
            loader.LoadVisualDM("..\\..\\..\\..\\..\\IDE\\IDEMainForm\\bin\\Debug\\Типовые описания оборудования\\TADiOM\\TADiOM.main.vdm");//".\\RMSI\\RMSI.main.vdm" ".\\ForLitie\\MILP.main.vdm"
//            loader.LoadVisualDM(".\\RMSI\\RMSI.main.vdm"/*".\\TADiOM\\TADiOM.main.vdm"*/);//".\\RMSI\\RMSI.main.vdm" ".\\ForLitie\\MILP.main.vdm"
        }

        private void InitializeMessageFilter()
        {
            keyFilter = new KeyPressMessageFilter();
            Application.AddMessageFilter(keyFilter);
        }

        private void InitializeVisualization()
        {
            var vdm = ecoSpace.Ocl.Evaluate("VisualDomainModel.allInstances->first").AsObject as VisualDomainModel;
            VisualManager = new Visualizator.Visualizator(ecoSpace, this, vdm);

            //-33,8; 0; 9.399998

/*            VisibleSceneObject o1 = new VisibleSceneObject(ecoSpace) { Name = "Table_BolvDown", ID = 0x1834 };
            MeshResource mres;
            o1.DefaultPosition.Vector = new Vector3(-33.8f, 0.0f, 9.399998f);
            o1.DefaultOrientation.Quaternion = Quaternion.Identity;
            o1.DefaultScale.Vector = new Vector3(1, 1, 1);
            o1.TypeModelling = 0x0003;
            mres = new MeshResource(ecoSpace) { FileName = "TADiOM_BDownTable.mesh" };
            o1.AddResource(mres);
            VisualManager.VDM.Scene.AddChildSceneObject(o1);*/


/*            VisibleSceneObject o1 = new VisibleSceneObject(ecoSpace) { Name = "Table2_3", ID = 0x1798 };
            MeshResource mres;
            o1.DefaultPosition.Vector = new Vector3(0.0f, 0.0f, 0.0f);
            o1.DefaultOrientation.Quaternion = Quaternion.Identity;
            o1.DefaultScale.Vector = new Vector3(1, 1, 1);
            o1.TypeModelling = 0x0003;
            mres = new MeshResource(ecoSpace) { FileName = "Tadiom_Table2.mesh" };
            o1.AddResource(mres);
            VisualManager.VDM.Scene.AddChildSceneObject(o1);*/

/*            VisibleSceneObject s = (VisibleSceneObject)VisualManager.VDM.FindSceneObject("Table2_2", 0x1797);
            int i=0;
            if (s.Resources != null)
            {
                while (s.Resources.Count != 0)
                {
                    s.Resources[i].AsIObject().Delete();
                    i++;
                }
            }
            s.AsIObject().Delete();*/

            

/*            VisibleSceneObject o2 = new VisibleSceneObject(ecoSpace) { Name = "GantryRobot_Platform", ID = 0x1110 };
            o2.DefaultPosition.Vector = new Vector3(150.0f, 150.0f, 0.0f);
            o2.DefaultOrientation.Quaternion = Quaternion.Identity;//.FromAngleAxis(Utility.DegreesToRadians(0), Vector3.UnitX);
            o2.DefaultScale.Vector = new Vector3(1, 1, 1);
            o2.TypeModelling = 0;
            mres = new MeshResource(ecoSpace) { FileName = "RMSI_MP9Stan.mesh" };
            o2.AddResource(mres);

            script = new VisualDM.Model.Animation(ecoSpace)
            {
                Name = "Go",
                LuaCode = @"
PincersOpen = coroutine.create(function ()
    local axis = 0;
    Modelling:PinStateChanged(3, 1);
end)",
                MethodID = "1"
            };
            o2.AddAnimation(script);

            script = new VisualDM.Model.Animation(ecoSpace)
            {
                Name = "GantryRobot_Finger_Open",
                LuaCode = @"
GantryRobot_Finger_Open= coroutine.create(function ()
    local axis = 0;
    Modelling:PinStateChanged(3, 1);
end)",
                MethodID = "1"
            };
            o2.AddAnimation(script);

            script = new VisualDM.Model.Animation(ecoSpace)
            {
                Name = "GantryRobot_Finger_Close",
                LuaCode = @"
GantryRobot_Finger_Close= coroutine.create(function ()
    local axis = 0;
    Modelling:PinStateChanged(3, 1);
end)",
                MethodID = "1"
            };
            o2.AddAnimation(script);

            o1.AddChildSceneObject(o2);

            VisibleSceneObject o3 = new VisibleSceneObject(ecoSpace) { Name = "GantryRobot_Fingers1", ID = 0x1101 };
            o3.DefaultPosition.Vector = new Vector3(6f, 0, 8f);
            o3.DefaultOrientation.Quaternion = Quaternion.FromAngleAxis(Utility.DegreesToRadians(15), Vector3.UnitY);
            o3.DefaultScale.Vector = new Vector3(1, 1, 1);
            mres = new MeshResource(ecoSpace) { FileName = "RMSI_MP11Finger.mesh" };
            o3.AddResource(mres);
            o2.AddChildSceneObject(o3);
            
            o3 = new VisibleSceneObject(ecoSpace) { Name = "GantryRobot_Fingers2", ID = 0x1102 };
            o3.DefaultPosition.Vector = new Vector3(6f, 0, 8f);
            o3.DefaultOrientation.Quaternion = Quaternion.FromAngleAxis(Utility.DegreesToRadians(15), Vector3.UnitY);
            o3.DefaultScale.Vector = new Vector3(1, 1, 1);
            mres = new MeshResource(ecoSpace) { FileName = "RMSI_MP11Finger.mesh" };
            o3.AddResource(mres);
            o2.AddChildSceneObject(o3);

/*            VisualDM.Model.Animation script;

            VisibleSceneObject o1 = new VisibleSceneObject(ecoSpace) { Name = "Pincers", ID = 0x1000 };
            MeshResource mres;
            o1.DefaultPosition.Vector = new Vector3(50.0f, 50.0f, 0.0f);
            o1.DefaultOrientation.Quaternion = Quaternion.Identity;//.FromAngleAxis(Utility.DegreesToRadians(0), Vector3.UnitX);
            o1.DefaultScale.Vector = new Vector3(1, 1, 1);
            o1.TypeModelling = 0;
            mres = new MeshResource(ecoSpace) { FileName = "RMSI_MP9Stan.mesh" };
            o1.AddResource(mres);

            script = new VisualDM.Model.Animation(ecoSpace)
            {
                Name = "PincersOpen",
                LuaCode = @"
PincersOpen = coroutine.create(function ()
    local axis = 0;
    Modelling:PinStateChanged(3, 1);
end)",
                MethodID = "1"
            };
            o1.AddAnimation(script);
            script = new VisualDM.Model.Animation(ecoSpace)
            {
                Name = "PincersClose",
                LuaCode = @"
PincersClose = coroutine.create(function ()
    local axis = 0;
    Modelling:PinStateChanged(3, 0);
end)",
                MethodID = "2"
            };
            o1.AddAnimation(script);

            VisualManager.VDM.Scene.AddChildSceneObject(o1);

            VisibleSceneObject o2 = new VisibleSceneObject(ecoSpace) { Name = "PincersLFinger", ID = 0x1001 };
            o2.DefaultPosition.Vector = new Vector3(6f, 0, 8f);
            o2.DefaultOrientation.Quaternion = Quaternion.FromAngleAxis(Utility.DegreesToRadians(15), Vector3.UnitY);
            o2.DefaultScale.Vector = new Vector3(1, 1, 1);
            mres = new MeshResource(ecoSpace) { FileName = "RMSI_MP11Finger.mesh" };
            o2.AddResource(mres);
            o1.AddChildSceneObject(o2);

            o2 = new VisibleSceneObject(ecoSpace) { Name = "PincersRFinger", ID = 0x1002 };
            o2.DefaultPosition.Vector = new Vector3(6f, 0, 8f);
            o2.DefaultOrientation.Quaternion = Quaternion.FromAngleAxis(Utility.DegreesToRadians(60), Vector3.UnitY);
            o2.DefaultScale.Vector = new Vector3(1, 1, 1);
            mres = new MeshResource(ecoSpace) { FileName = "RMSI_MP11Finger.mesh" };
            o2.AddResource(mres);
            o1.AddChildSceneObject(o2);*/



/*            VisibleSceneObject o1 = new VisibleSceneObject(ecoSpace) { Name = "CastingTray", ID = 0x900 };
            MeshResource mres;
            o1.DefaultPosition.Vector = new Vector3(50.0f, 50.0f, 0.0f);
            o1.DefaultOrientation.Quaternion = Quaternion.Identity;//.FromAngleAxis(Utility.DegreesToRadians(0), Vector3.UnitX);
            o1.DefaultScale.Vector = new Vector3(1, 1, 1);
            o1.TypeModelling = 4;
            mres = new MeshResource(ecoSpace) { FileName = "TrayCasting.mesh" };
            o1.AddResource(mres);
            VisualManager.VDM.Scene.AddChildSceneObject(o1);*/


/*            VisibleSceneObject o1 = new VisibleSceneObject(ecoSpace) { Name = "Bolv_Cylinder1", ID = 0x400 };
            o1.DefaultPosition.Vector = new Vector3(-50f, 19f, 51f);
            o1.DefaultOrientation.Quaternion = Quaternion.Identity;
            o1.DefaultScale.Vector = new Vector3(1f, 1f, 1f);
            MeshResource mres = new MeshResource(ecoSpace) { FileName = "RMSI_Bolv.mesh" };
            o1.AddResource(mres);
            VisualManager.VDM.Scene.AddChildSceneObject(o1);

            o1 = new VisibleSceneObject(ecoSpace) { Name = "Bolv_Cylinder2", ID = 0x401 };
            o1.DefaultPosition.Vector = new Vector3(-5f, 19f, 51f);
            o1.DefaultOrientation.Quaternion = Quaternion.Identity;
            o1.DefaultScale.Vector = new Vector3(1f, 1f, 1f);
            mres = new MeshResource(ecoSpace) { FileName = "RMSI_Bolv.mesh" };
            o1.AddResource(mres);
            VisualManager.VDM.Scene.AddChildSceneObject(o1);

            o1 = new VisibleSceneObject(ecoSpace) { Name = "Support1", ID = 0x402, TypeModelling = 1 };
            o1.DefaultPosition.Vector = new Vector3(-10f, -10f, 70f);

            o1.DefaultOrientation.Quaternion = new Quaternion(0.6532815f, -0.6532815f, 0.2705981f, 0.2705981f);

            o1.DefaultScale.Vector = new Vector3(2.1f, 2.9f, 2.7f);
            mres = new MeshResource(ecoSpace) { FileName = "RMSI_Support1.mesh" };
            o1.AddResource(mres);
            VisualManager.VDM.Scene.AddChildSceneObject(o1);

            o1 = new VisibleSceneObject(ecoSpace) { Name = "RMSI_Support2", ID = 0x403 };
            o1.DefaultPosition.Vector = new Vector3(-140, -10, 55);
            o1.DefaultOrientation.Quaternion = new Quaternion(0.5f, -0.5f, -0.5f, -0.5f);
            o1.DefaultScale.Vector = new Vector3(2.5f, 2.2f, 2.7f);
            mres = new MeshResource(ecoSpace) { FileName = "RMSI_Support2.mesh" };
            o1.AddResource(mres);
            VisualManager.VDM.Scene.AddChildSceneObject(o1);*/

            CameraSceneObject cam = new CameraSceneObject(ecoSpace) { Name = "Main_Camera", ID = 0x01 };
            cam.DefaultPosition.Vector = new Vector3(27.2331f, 59.00272f, 114.2085f); //new Vector3(64.28306f, 96.96927f, 177.968857f);// new Vector3(0f, 200f, 0f);
//            cam.DefaultDirection.Vector = Vector3.Zero;
            cam.DefaultLookAt.Vector = new Vector3(26.6222929f, 58.528138f, 113.5747128f);
//            cam.LookAt(new Vector3(0f,0f,0f));
//            26.6222929f  58.528138 113.5747128

            DirectionalLightSceneObject l = new DirectionalLightSceneObject(ecoSpace) { Name = "Main_Light", ID = 0x02 };
            l.Color.Color = new ColorEx(0.5f, 0.5f, 0.5f);
            l.DefaultPosition.Vector = new Vector3(500, 500, 500);
            l.Direction.Vector = new Vector3(-1, -1, -1);
            l.Specular.Color = new ColorEx(0.859375f, 0.9843137f, 0f);
            l.Diffuse.Color = new ColorEx(0.4765625f, 0.43359375f, 0.38671875f);


            VisualManager.AddSceneObject(l);

            VisualManager.AddRenderWindow(visualizationTarget, cam);
            vdm.Initialize(VisualManager.sceneManager);
            visualizationTimer.Tick += new EventHandler(visualizationTimer_Tick);
            visualizationTimer.Enabled = true;
            keyFilter.Subscribe(new KeyPressEventHandler(VisualManager.HandleKeyPress));
            VisualManager.StartRender();

            //ecoSpace.GetEcoService<ISystemTimer>().Subscribe(new EventHandler(OnTick));
            //pictureBox1.BeginInvoke(new MethodInvoker(VisualManager.StartRender));
        }

        private void VDMEditor_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (VisualManager != null)
            {
                SceneObject s = VisualManager.VDM.FindSceneObject("Main_Camera",0x01);
                s.AsIObject().Delete();
//                s.Parent.ChildSceneObjects.Remove(s);
                s = VisualManager.VDM.FindSceneObject("Main_Light", 0x02);
                s.AsIObject().Delete();
//                s.Parent.ChildSceneObjects.Remove(s);

                var loader = new VisualDMLoader(ecoSpace);
                loader.SaveVisualDMToFile(Path.GetDirectoryName(Application.ExecutablePath) + @"\querys", @"..\..\..\..\..\IDE\IDEMainForm\bin\Debug\Типовые описания оборудования\TADiOM\TADiOM.main.vdm"); //".\\RMSI\\RMSI.main.vdm" "ForLitie\MILP.main.vdm"
//                loader.SaveVisualDMToFile(Path.GetDirectoryName(Application.ExecutablePath) + @"\querys", @".\\RMSI\\RMSI.main.vdm"/*@"TADiOM\TADiOM.main.vdm"*/); //".\\RMSI\\RMSI.main.vdm" "ForLitie\MILP.main.vdm"
                VisualManager.FreeRenderContext();
            }
        }

        private void FillTreeNodeObjects(SceneObject o, TreeNode node)
        {
            foreach (SceneObject s in o.ChildSceneObjects)
            {
                TreeNode nod = new TreeNode(s.Name);
                FillTreeNodeObjects(s, nod);
                nod.Tag = s;
                node.Nodes.Add(nod);
            }
        }

        private void FillTreeViewObjects(SceneObject o)
        {
                treeView1.Nodes.Clear();
                TreeNode nod = new TreeNode(o.Name);
                FillTreeNodeObjects(o, nod);
                nod.Tag = o;
                treeView1.Nodes.Add(nod);
        }

        private void VDMEditor_Load(object sender, EventArgs e)
        {
            InitializeVisualization();
            FillTreeViewObjects(VisualManager.VDM.Scene);
        }

        private void visualizationTimer_Tick(object sender, EventArgs e)
        {
            VisualManager.RenderFrame();
        }

        private void VDMEditor_FormClosed(object sender, FormClosedEventArgs e)
        {
            main_log.Dispose();
        }

        private void RefreshInformation()
        {
            if (SelectedObject != null)
            {
                XCoordLabel.Text = "X : " + SelectedObject.SceneNode.Position.x.ToString();
                YCoordLabel.Text = "Y : " + SelectedObject.SceneNode.Position.y.ToString();
                ZCoordLabel.Text = "Z : " + SelectedObject.SceneNode.Position.z.ToString();
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (SelectedObject!=null)
                SelectedObject.SceneNode.ShowBoundingBox = false;
            SelectedObject = e.Node.Tag as SceneObject;
            RefreshInformation();
            SelectedObject.SceneNode.ShowBoundingBox = true;
            tvScriptList.Nodes.Clear();
            foreach (VisualDM.Model.Animation s in SelectedObject.Animations)
            {
                TreeNode n = new TreeNode(s.Name);
                n.Tag = s;
                tvScriptList.Nodes.Add(n);
            }
            textBox1.Text = "";
            numericUpDown2.Value = 0;
            numericUpDown1.Value = 0;
            richTextBox1.Text = "";
            SelectedScript = null;
        }

        private void TranslateButton_Click(object sender, EventArgs e)
        {
            if (SelectedObject != null)
            {
                SelectedObject.Translate(float.Parse(TranslateXtextBox.Text), float.Parse(TranslateYtextBox.Text), float.Parse(TranslateZtextBox.Text));
                SelectedObject.DefaultPosition.Vector = new Vector3(SelectedObject.SceneNode.Position.x, SelectedObject.SceneNode.Position.y, SelectedObject.SceneNode.Position.z);
                RefreshInformation();
            }
        }

        private void TranslateXtextBox_TextChanged(object sender, EventArgs e)
        {
            TranslateXtextBox.Focus();
        }

        private void TranslateYtextBox_TextChanged(object sender, EventArgs e)
        {
            TranslateYtextBox.Focus();
        }

        private void TranslateZtextBox_TextChanged(object sender, EventArgs e)
        {
            TranslateZtextBox.Focus();
        }

        private void visualizationTarget_Click(object sender, EventArgs e)
        {
            visualizationTarget.Focus();
        }

        private void ScaleButon_Click(object sender, EventArgs e)
        {
            if (SelectedObject != null)
            {
                ScaleXTextBox.Text.Replace('.',',');
                ScaleYTextBox.Text.Replace('.', ',');
                ScaleZTextBox.Text.Replace('.', ',');

                SelectedObject.Scale(new Vector3(float.Parse(ScaleXTextBox.Text), float.Parse(ScaleYTextBox.Text), float.Parse(ScaleZTextBox.Text)));
                SelectedObject.DefaultScale.Vector = new Vector3(SelectedObject.SceneNode.ScaleFactor.x, SelectedObject.SceneNode.ScaleFactor.y, SelectedObject.SceneNode.ScaleFactor.z);
                RefreshInformation();
            }
        }

        private void RotateButton_Click(object sender, EventArgs e)
        {
            if (SelectedObject != null)
            {
                SelectedObject.Rotate(float.Parse(RotateXTextBox.Text), float.Parse(RotateYTextBox.Text), float.Parse(RotateZTextBox.Text), float.Parse(RotateAngleTextBox.Text));
                SelectedObject.DefaultOrientation.Quaternion = new Quaternion(SelectedObject.SceneNode.Orientation.w, SelectedObject.SceneNode.Orientation.x, SelectedObject.SceneNode.Orientation.y, SelectedObject.SceneNode.Orientation.z);
                RefreshInformation();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SceneObject s = VisualManager.VDM.FindSceneObject(SelectedObject.Name, SelectedObject.ID);
            int k = s.Animations.Count;
            for (int i = 0; i < k; i++)
            {
                s.Animations[s.Animations.Count - 1].AsIObject().Delete();
            }

            s.AsIObject().Delete();
        }

        /// <summary>
        /// Создать новый скрипт и добавить его к текущему выделенному объекту, обновив на формочке соответствующие поля
        /// </summary>
        private void AddNewScript()
        {
            if (SelectedObject == null)
            {
                MessageBox.Show("No selected object", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            VisualDM.Model.Animation newScript = CreateNewScript("", "0", 0, "NoName");
            SelectedObject.AddAnimation(newScript);
            SelectedScript = newScript;
            RefreshScriptInformation();
            RefreshScriptList();
        }

        /// <summary>
        /// Создать новый скрипт
        /// </summary>
        /// <param name="luaCode">код скрипта</param>
        /// <param name="MethodID">привязка к методу</param>
        /// <param name="needConnect">привязка к узлу</param>
        /// <param name="name">название скрипта</param>
        /// <returns></returns>
        private VisualDM.Model.Animation CreateNewScript(string luaCode, string MethodID, int needConnect, string name)
        {
            VisualDM.Model.Animation newSC = new VisualDM.Model.Animation(ecoSpace);
            newSC.LuaCode = luaCode;
            newSC.MethodID = MethodID;
            newSC.NeedConnect = needConnect;
            newSC.Name = name;
            return newSC;
        }
        
        /// <summary>
        /// Обновить список скриптов текущего объекта
        /// </summary>
        private void RefreshScriptList()
        {
            tvScriptList.Nodes.Clear();
            foreach (VisualDM.Model.Animation sc in SelectedObject.Animations)
            {
                TreeNode node = new TreeNode(sc.Name);
                node.Tag = sc;
                tvScriptList.Nodes.Add(node);    
            }
            tvScriptList.SelectedNode = tvScriptList.Nodes[tvScriptList.Nodes.Count - 1];
            tvScriptList.SelectedNode.BackColor = SystemColors.Highlight;
            tvScriptList.SelectedNode.ForeColor = SystemColors.HighlightText;
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Обновить  на формочке информацию о скрипте 
        /// </summary>
        public void RefreshScriptInformation()
        {
            textBox1.Text = SelectedScript.Name;
            numericUpDown2.Value = SelectedScript.NeedConnect;
            numericUpDown1.Value = int.Parse(SelectedScript.MethodID);
            richTextBox1.Text = SelectedScript.LuaCode;
        }

        private void treeView2_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (SelectedObject != null)
            {
                SelectedScript = e.Node.Tag as VisualDM.Model.Animation;
                RefreshScriptInformation();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (SelectedScript == null)
                return;
            SelectedScript.LuaCode = new string(richTextBox1.Text.ToCharArray());
            SelectedScript.MethodID = new string(numericUpDown1.Value.ToString().ToCharArray());
            SelectedScript.NeedConnect = (int)numericUpDown2.Value;
            SelectedScript.Name = new string(textBox1.Text.ToCharArray());

            tvScriptList.Nodes.Clear();            
            foreach (VisualDM.Model.Animation s in SelectedObject.Animations)
            {
                TreeNode n = new TreeNode(s.Name);
                n.Tag = s;
                tvScriptList.Nodes.Add(n);
                if (SelectedScript == s)
                    tvScriptList.SelectedNode = n;
            }
            tvScriptList.SelectedNode.BackColor = SystemColors.Highlight;
            tvScriptList.SelectedNode.ForeColor = SystemColors.HighlightText;
        }

        private void treeView2_Enter(object sender, EventArgs e)
        {
            if (tvScriptList.SelectedNode != null)
            {
                tvScriptList.SelectedNode.BackColor = SystemColors.Window;
                tvScriptList.SelectedNode.ForeColor = SystemColors.WindowText;
            }
        }

        private void treeView2_Leave(object sender, EventArgs e)
        {
            if (tvScriptList.SelectedNode == null) return;
            {
                tvScriptList.SelectedNode.BackColor = SystemColors.Highlight;
                tvScriptList.SelectedNode.ForeColor = SystemColors.HighlightText;
            }

        }

        private void treeView1_Enter(object sender, EventArgs e)
        {
            if (tvScriptList.SelectedNode != null)
            {
                tvScriptList.SelectedNode.BackColor = SystemColors.Window;
                tvScriptList.SelectedNode.ForeColor = SystemColors.WindowText;
            }

        }

        private void treeView1_Leave(object sender, EventArgs e)
        {
            if (tvScriptList.SelectedNode == null) return;
            {
                tvScriptList.SelectedNode.BackColor = SystemColors.Highlight;
                tvScriptList.SelectedNode.ForeColor = SystemColors.HighlightText;
            }

        }
        //После того как вызвалось  нажатие кнопки "Переместить узел в", то ОБЯЗАТЕЛЬНО НУЖНО ПЕРЕЗАПУСТИТЬ ПРИЛОЖЕНИЕ!
        private void button5_Click(object sender, EventArgs e)
        {
            if (SelectedObject != null)
            {
                if (SwapObject == null)
                    SwapObject = SelectedObject;
                else
                {
                    if (SelectedObject != SwapObject)
                    {
                        SceneObject s = SelectedObject;
                        SceneObject Parent = SwapObject.Parent;
                        SceneNode sn = s.SceneNode;

//                        SelectedObject.Parent.ChildSceneObjects.Remove(SelectedObject);
                        SwapObject.Parent.ChildSceneObjects.Remove(SwapObject);
                        Parent.SceneNode.RemoveChild(SwapObject.SceneNode.Name);
                        SelectedObject.AddChildSceneObject(SwapObject);
                        SelectedObject.SceneNode.AddChild(SwapObject.SceneNode);
                        
//                        SelectedObject.ChildSceneObjects.Add(SwapObject);
                        //Parent.AddChildSceneObject(SelectedObject);
/*                        SwapObject.Parent.SceneNode.AddChild(SwapObject.SceneNode);
                        SelectedObject.Parent.SceneNode.AddChild(sn);*/

                        FillTreeViewObjects(VisualManager.VDM.Scene);
                        RefreshInformation();
                        Parent.SceneNode.NeedUpdate();
                        SelectedObject.SceneNode.NeedUpdate();
                    }
                }
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (SelectedObject != null)
            {
                SelectedObject.Name = textBox2.Name;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddNewScript();
        }

        private void btnSaveExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        } 
    }
}